//
//  HomeViewController.swift
//  MMTest
//
//  Created by liujianlong on 2022/9/19.
//

import UIKit
import CoreBluetooth

class HomeViewController: EPViewController {
    var rightBtn:UIButton?
    @IBOutlet var startBtn: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        scan {[weak self] in
            self?.tableView.reloadData()

        }
    }
    override func initUI() {
        self.title = LS("首页")
        self.startBtn.isEnabled = true
        self.backBtn?.isHidden = true
        self.rightBtn = UIButton(type: .custom)
        self.rightBtn?.tag = 302
        self.rightBtn?.frame = CGRect(x: 0, y: kUIStatusBarHeight + 5, width: 70, height: 34)
        self.rightBtn?.addTarget(self, action: #selector(actionForBtn), for: .touchUpInside)
        self.rightBtn?.setTitle(LS("历史数据"), for: .normal)
        self.rightBtn?.setTitleColor("#005BBA".color(), for: .normal)
        self.rightBtn?.titleLabel?.font = font(14)
        let backItem = UIBarButtonItem(customView: self.rightBtn!)
        self.navigationItem.rightBarButtonItem = backItem
        self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.black, .font:font(18)]
        
        self.tableViewStyle = .grouped
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.hiddenMJRefresh()
        self.tableView.tableHeaderView = UIView(frame: .zero)
        self.tableView.register(HomeCell.nib(), forCellReuseIdentifier: HomeCell.ID())
        self.tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview().inset(20)
            make.bottom.equalTo(self.startBtn.snp.top).offset(-20)
        }
    }
    
    @objc @IBAction func actionForBtn(_ sender: UIButton) {
        self.action(sender, "")
    }
    
    func action(_ sender: UIButton, _ mac:String){
        var p : CBPeripheral?
        if mac.count > 0{
            let array = BLE.connectedPeripherals.filter{$0.mac == mac}
            p = array.first
        }
        if p == nil && mac != ""{return}
        switch sender.tag{
        case 201:///重启设备
            RLHud.start("重启设备中,请勿重复重启")
            if p == nil{return}
            BLEData.reboot.write(p!)
        case 202:///断开
            if p == nil{return}
            //APP.array.removeAll{$0.mac == mac}
            APP.singleData = SingleData()
            BLE.disConnect(p!)
        case 203:///归零
            EPAlertPopViewController.pop(LS("注意"), LS("请举起设备，确认当前未对设备施加外力"), .withCancel) { tag, text in
                BLEData.clear.write(p!)
            }
        case 301:///开始记录
            APP.stamp = NSDate.currentTimeStamp("yyyy/MM/dd HH:mm:ss")
            APP.start = true
            let vc = StartViewController()
            self.push(vc, true)
        case 302:///历史数据
            let vc = RecordViewController()
            self.push(vc, true)
        default:
            break
        }
    }
    
}
//MARK: - 蓝牙相关通知
extension HomeViewController{
    override func addNotify() {
        NotifyTool.add(self, #selector(actionForBLEStatusUpdate), BLEStatusUpdateNotifyName)
        NotifyTool.add(self, #selector(actionForBLESDataUpdate), BleDataUpdateNotifyName)
    }
    
    @objc func actionForBLEStatusUpdate(){
        DispatchQueue.main.async {
            if BLE.status == .connectedFail{
                APP.singleData = SingleData()
                self.pop(LS("提示"), LS("蓝牙已断开！"), .onlyOK) { tag, text in
                    self.navigationController?.popToRootViewController(animated: true)
                }
            }else if BLE.status == .disconnect{
                RLHud.start("已断开", stopTime: 1, handle: nil)
                self.tableView.reloadData()
                return
            }
            if self.currentVC() == self{
                RLHud.stop()
            }
            self.tableView.reloadData()
        }
    }
    
    @objc func actionForBLESDataUpdate(){
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
}

//MARK: - UITableViewDataSource
extension HomeViewController : UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: HomeCell.ID()) as! HomeCell
        weak var weakself = self
        cell.bgView.isHidden = APP.singleData.mac.count > 0
        cell.name.text = APP.singleData.deviceName
        cell.content.text = String(format:LS("实时L:%dg 最大L:%dg 平均L:%dg 计步L:%d步\n实时R:%dg 最大R:%dg 平均R:%dg 计步R:%d步\n温度:%d 气压:%d 杖类型:%d"), APP.singleData.l_current,APP.singleData.l_max,APP.singleData.l_avg,APP.singleData.l_step, APP.singleData.r_current,APP.singleData.r_max,APP.singleData.r_avg,APP.singleData.r_step,APP.singleData.temperature,APP.singleData.airPressure,APP.singleData.type)
        cell.electNum.text = "电量L：\(APP.singleData.l_batterlevel)%   电量R：\(APP.singleData.r_batterlevel)%"
        cell.block = { button in
            weakself?.action(button, APP.singleData.mac)
        }
        self.startBtn.isEnabled = APP.singleData.mac.count > 0
        self.startBtn.bgHexColor = APP.singleData.mac.count > 0 ? "#092D74" : "#CFCFCF"
        return cell
    }
    
    
}
//MARK: - UITableViewDelegate
extension HomeViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! HomeCell
        if cell.bgView.isHidden == false {
            let vc = SearchViewController()
            self.push(vc, true)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
